package com.ty.xiaoyu.service.impl;

import com.ty.xiaoyu.entity.User;
import com.ty.xiaoyu.exception.UserOperationException;
import com.ty.xiaoyu.service.UserService;
import com.ty.xiaoyu.util.MyTimeUtil;
import com.ty.xiaoyu.util.RandomIdUtil;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends BaseService implements UserService {
    @Override
    public User getUserById(String userId) {
        return userMapper.queryUserById(userId);
    }

    @Override
    public User getUserByUserNameAndPassword(String UserName, String password) throws UserOperationException {
        User user = userMapper.queryUserByUserNameAndPassword(UserName, password);
        if (user == null) {
            throw new UserOperationException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public void addUser(User user) throws UserOperationException {
        user.setUserId(RandomIdUtil.getId());
        user.setRegisterTime(MyTimeUtil.nowTime());
        user.setUpdateTime(MyTimeUtil.nowTime());
        user.setUserRole(0);
        user.setUserState(1);
        user.setNickname(user.getUserName());
        user.setLastLoginTime(MyTimeUtil.nowTime());
        user.setLastLogoutTime(MyTimeUtil.nowTime());
        Integer state = userMapper.addUser(user);
        if (state <= 0) {
            throw new UserOperationException("注册失败");
        }
    }

    @Override
    public void getUserByName(String userName) throws UserOperationException {
        Integer number = userMapper.queryUserCountByName(userName);
        if (number > 0) {
            throw new UserOperationException("用户名已存在");
        }
    }

    @Override
    public void modifyUser(User user) throws UserOperationException {
        user.setUpdateTime(MyTimeUtil.nowTime());
        Integer state = userMapper.updateUser(user);
        if (state <= 0) {
            throw new UserOperationException("修改信息失败");
        }
    }

    @Override
    public void modifyUserLastLog(User user) throws UserOperationException {
        Integer state = userMapper.updateUserLastLog(user);
        if (state <= 0) {
            throw new UserOperationException("修改用户最后登陆、注销时间失败");
        }
    }
}
